﻿using BSChuangXu.API.Read.Appicant.Commend.MenuCommend;
using BSChuangXu.API.Read.DTO;
using BSChuangXu.Domain.User;
using BSChuangXu.ErrorCode;
using BSChuangXu.Infrastructure.Interface;
using MediatR;

namespace BSChuangXu.API.Read.Appicant.CommendHandel.MenuCommandHandler
{
    /// <summary>
    /// 菜单列表命令执行
    /// </summary>
    public class GetMenuCommandHandler : IRequestHandler<GetMenuCommend, APIResult<List<MenuDto>>>
    {
        private readonly IBaseRepository<MenuModel> menuRepos;
        public GetMenuCommandHandler(IBaseRepository<MenuModel> menuRepos)
        {
            this.menuRepos = menuRepos;
        }
        /// <summary>
        /// 菜单列表显示(排序)
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<List<MenuDto>>> Handle(GetMenuCommend request, CancellationToken cancellationToken)
        {
            APIResult<List<MenuDto>> result = new APIResult<List<MenuDto>>();
            var list = from a in menuRepos.GetAll().Result
                       join b in menuRepos.GetAll().Result
                       on a.ParentId equals b.MenuId
                       where a.IsDel == false
                       select new MenuDto
                       {
                           MenuId = a.MenuId,
                           ParentId = a.ParentId,
                           MenuName = a.MenuName,
                           Url = a.Url,
                           CreateName = a.CreateName,
                           CreateTime = a.CreateTime,
                           UpdateName = a.UpdateName,
                           UpdateTime = a.UpdateTime,
                           IsDeleted = a.IsDel,
                           ParentName = b.MenuName,
                           OrderNum = a.OrderNum,
                       };
            result.data = list.OrderByDescending(x => x.OrderNum).ToList();
            return await Task.FromResult(result);
        }
    }
}
